<template>
  <div class="time_picker">
    <el-input
      :style="{width: inputWidth+'px'}"
      v-model="timeHour"
      @change="limit('timeHour', arguments[0], 0, 24)"></el-input>
    <span>{{timeType||'时'}}</span>
    <el-input
      :style="{width: inputWidth+'px'}"
      v-model="timeMinute"
      @change="limit('timeMinute', arguments[0], 0, 60)"></el-input>
    <span>{{timeType||'分'}}</span>
    <el-input
      :style="{width: inputWidth+'px'}"
      v-model="timeSecond"
      @change="limit('timeSecond', arguments[0], 0, 60)"></el-input>
    <span v-if="!timeType">秒</span>
  </div>
</template>

<script>
const timeFull = (t) => {
  return !t ? '00' : t >= 10 ? t : '0' + t
}
const util_number = {
  formatter(value) {
    if (!value) return ''
    return '' + value
  },
  parser(text) {
    if (!isNaN(text)) {
      let result = Number(text)
      return result
    } else {
      return null
    }
  }
}
export default {
  props: {
    timeVal: {
      type: String,
      default: ''
    },
    typeStr: {
      type: String,
      default: ':'
    },
    inputWidth: {
      type: String,
      default: '50'
    }
  },
  data() {
    return {
      timeHour: 0,
      timeMinute: 0,
      timeSecond: 0,
      timeType: ''
    }
  },
  watch: {
    typeStr: {
      handler(val) {
        if (val) {
          this.timeType = val
        } else {
          this.timeType = ''
        }
      },
      immediate: true
    },
    timeVal: {
      handler(val) {
        // console.log(val)
        this.initTime(val)
      },
      immediate: true
    }
  },
  methods: {
    limit(el, val, min, max) {
      this.$nextTick(() => {
        val = util_number.parser(parseInt(val))
        val = val || 0
        if (val > max) {
          val = Math.min(val, max)
        } else if (val < min) {
          val = Math.max(val, min)
        }
        this[`${el}`] = timeFull(val)
        this.displayValue()
      })
    },
    initTime(val) {
      if (val) {
        const t = val.split(this.typeStr || ':')
        this.resetTime(t[0], t[1], t[2])
      } else {
        this.resetTime()
      }
    },
    resetTime(h, m, s) {
      this.timeHour = timeFull(util_number.parser(h)) || '00'
      this.timeMinute = timeFull(util_number.parser(m)) || '00'
      this.timeSecond = timeFull(util_number.parser(s)) || '00'
    },
    displayValue() {
      let h = util_number.parser(this.timeHour)
      let m = util_number.parser(this.timeMinute)
      let s = util_number.parser(this.timeSecond)
      let val = ''
      if (h || m || s) {
        h = timeFull(h)
        m = timeFull(m)
        s = timeFull(s)
        if (this.typeStr) {
          val = `${h}${this.typeStr}${m}${this.typeStr}${s}`
        }
        val = `${h}:${m}:${s}`
      }
      this.emitInput(val)
    },
    emitInput(val) {
      this.$emit('input', val)
    }
  }
}
</script>

<style lang="scss" scoped>
.time_picker{
  display: inline-block;
}
</style>
